<?php require_once('../Connections/Admin.php'); ?>
<?php require_once('../Connections/media.php'); ?>
<?php require_once('../Connections/juventud.php'); ?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
include('funciones.php');
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$colname_datosUser = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_datosUser = $_SESSION['MM_Username'];
}
mysql_select_db($database_Admin, $Admin);
$query_datosUser = sprintf("SELECT * FROM users WHERE email = %s", GetSQLValueString($colname_datosUser, "text"));
$datosUser = mysql_query($query_datosUser, $Admin) or die(mysql_error());
$row_datosUser = mysql_fetch_assoc($datosUser);
$totalRows_datosUser = mysql_num_rows($datosUser);

mysql_select_db($database_media, $media);
$query_rsAnunciosTabla = "SELECT * FROM media WHERE categoria = 'Anuncio' ORDER BY ID DESC";
$rsAnunciosTabla = mysql_query($query_rsAnunciosTabla, $media) or die(mysql_error());
$row_rsAnunciosTabla = mysql_fetch_assoc($rsAnunciosTabla);
$totalRows_rsAnunciosTabla = mysql_num_rows($rsAnunciosTabla);

mysql_select_db($database_juventud, $juventud);
$query_rsProgra = "SELECT * FROM programacion ORDER BY prograID DESC";
$rsProgra = mysql_query($query_rsProgra, $juventud) or die(mysql_error());
$row_rsProgra = mysql_fetch_assoc($rsProgra);
$totalRows_rsProgra = mysql_num_rows($rsProgra);

$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { 
	echo'<script>
		function encontrado(){
	alert("Acceso denegado, Inicia Sesion para ingresar");	
}
	encontrado();
	</script>
	
	<meta http-equiv="refresh" content="0;url=log/login.php">
	';
	
  exit;
}
//Ingreso de la programacion
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO programacion (diaProgra, horaProgra, generoProgra, ipCreacion, diaCreacion, user_agent, user_creacion) VALUES (%s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['diaProgra'], "text"),
                       GetSQLValueString($_POST['horaProgra'], "text"),
                       GetSQLValueString($_POST['generoProgra'], "text"),
                       GetSQLValueString($ipUsuario, "text"),
                       GetSQLValueString($fechaUsuario, "text"),
                       GetSQLValueString($userAgent, "text"),
                       GetSQLValueString($_SESSION['MM_Username'], "text")
					   /* GetSQLValueString($_SESSION['MM_Username'], "text")*/);

  mysql_select_db($database_juventud, $juventud);
  $Result1 = mysql_query($insertSQL, $juventud) or die(mysql_error());
  echo'<script>
		function encontrado(){
	alert("Registro exitosamente ingresado");	
}
	encontrado();
	</script>
	
	<meta http-equiv="refresh" content="0;url=./">
	';
}
//fin INgreso de la programacion

//Ingresar nuevo anuncio

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "upLoadMedia")) {
  $typeArchive=$_FILES['archivo']['type']; //Tipo de archivo con el cual estamos trabajando
	switch ($typeArchive){
				case "image/jpeg":
				case "image/jpg":
				case "image/gif":
				case "image/png":
		
		$rand06 = substr((md5(rand())),0, 6);//generar un strig aleatorio para encadenarcelo al nombre del archivo
		$newNameMedia = $rand06.'_'.$_FILES['archivo']['name']; //String con el nuevo nombre para asignar al archivo con extension
		$newNameMedia = quitar_espa($newNameMedia);
		$path_media = "..".DIRECTORY_SEPARATOR."media".DIRECTORY_SEPARATOR."anuncios".DIRECTORY_SEPARATOR;
		move_uploaded_file($_FILES['archivo']['tmp_name'],$path_media.$newNameMedia);//enviar el archivo a donde corresponde
	
  $insertSQL = sprintf("INSERT INTO media ( descriptions, categoria, date, ip, nombrearchivo, tipoMedia, user) VALUES ( %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['descriptions'], "text"),
                       GetSQLValueString("Anuncio", "text"),
					   GetSQLValueString($fechaUsuario, "text"),
					   GetSQLValueString($ipUsuario, "text"),
					   GetSQLValueString($newNameMedia, "text"),
					   GetSQLValueString($_FILES['archivo']['type'], "text"),
					   GetSQLValueString($_SESSION['MM_Username'], "text"));

  mysql_select_db($database_media, $media);
  $Result1 = mysql_query($insertSQL, $media) or die("Error en ejecutar la consulta: ".mysql_error());
 	echo'<script>function encontrado(){alert("Imagen subida exitosamente");}encontrado();</script>';
	echo '<meta http-equiv="refresh" content="0;url=./">';
				break;
				default:
					echo'<script>function encontrado(){alert("Tipo de archivo invalido, por favor intente de nuevo");}encontrado();</script>
					<meta http-equiv="refresh" content="0;url=./">
					';} 
}

//Fin nuevo anuncio


//Borrar registro

if ((isset($_GET['prograID'])) && ($_GET['prograID'] != "")) {
  $deleteSQL = sprintf("DELETE FROM programacion WHERE prograID=%s",
                       GetSQLValueString($_GET['prograID'], "int"));
					  
 mysql_select_db($database_juventud, $juventud);
  $Result1 = mysql_query($deleteSQL, $juventud) or die(mysql_error());
}
//FIn borrar registro




?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Inicio</title>
<link href="../css/AdminIndex.css" rel="stylesheet" type="text/css">
<script src="../SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
<link href="../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="header">BIENVENIDO <?php echo $row_datosUser['email']; ?></div><div style="clear:both;"></div>
<div class="menu">
    <ul id="MenuBar1" class="MenuBarHorizontal">
      <li><a href="./">Inicio</a>  </li>
      <li><a href="?url=radio">Radio</a></li>
      <li><a href="log/logout.php">Cerrar Sesi&oacute;n</a>      </li>
    </ul>
</div><br><br>
<?php 
	$direccion='';
	if(isset($_GET['url'])){
		switch($_GET['url']){
			case 'radio':
				$direccion='radio.php';
			break;
			}
	include ($direccion);
	}else{
	echo'
		<p>Aquí podras modificar solamente el subdominio de juventud</p>
	
	';
	}
	

?>
<script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"../SpryAssets/SpryMenuBarDownHover.gif", imgRight:"../SpryAssets/SpryMenuBarRightHover.gif"});
</script>
</body>
</html>
<?php
mysql_free_result($datosUser);

mysql_free_result($rsAnunciosTabla);

mysql_free_result($rsProgra);
?>
